package com.example.thread;

import java.text.SimpleDateFormat;
import java.util.Random;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: ZhangLiang
 * @Date: 2021/07/03/11:27
 * @Description: ThreadLocaldemo
 */
public class ThreadLocalDemo implements Runnable{
   private static final ThreadLocal<SimpleDateFormat> format=ThreadLocal.withInitial(()->new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));

    public static void main(String[] args) throws InterruptedException {
        ThreadLocalDemo runnable=new ThreadLocalDemo();

        for (int i = 0; i < 10; i++) {
            Thread thread=new Thread(runnable,""+i);
            Thread.sleep(new Random().nextInt(1000));
            thread.start();
        }
    }

    @Override
    public void run() {
        System.out.println("Thread Name= "+Thread.currentThread().getName()+" 日期默认格式= "+format.get().toPattern());
        try {
            Thread.sleep(new Random().nextInt(1000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        format.set(new SimpleDateFormat());
        System.out.println("Thread Name= "+Thread.currentThread().getName()+" 日期修改后格式= "+format.get().toPattern());

        //使用完 ThreadLocal方法后 最好手动调用remove()方法， 防止内存泄漏
        format.remove();
    }
}
